import { useState } from 'react'
import { Form, Input, Button } from 'antd'
import { useNavigate } from 'react-router'
import { login } from '@/api/login.js'
import { useDispatch } from 'react-redux'
import { setToken } from '@/store/slicers/user'

export default function Login() {
  // 登录按钮loading状态
  const [loading, setLoading] = useState(false)
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const onFinish = async (values) => {
    try {
      setLoading(true)
      // 这里可以做登录校验，成功后跳转
      console.log('Received values:', values)
      let res = await login(values)
      console.log('Login response:', res)
      dispatch(setToken(res.token))
      navigate('/')
    } catch (error) {
      console.error(error)
      setLoading(false)
    }
  }

    return (
    <div style={{ maxWidth: 320, margin: '100px auto', padding: 24, boxShadow: '0 2px 8px #f0f1f2', borderRadius: 8 }}>
      <Form name="login" onFinish={onFinish}>
        <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
          <Input placeholder="用户名" />
        </Form.Item>
        <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
          <Input.Password placeholder="密码" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" block loading={loading}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}
